#!/usr/bin/perl -w
# 


use strict;
use warnings;
use POSIX qw(:signal_h);
use Proc::Daemon;
use IO::Socket;
use Digest::MD5;
use MLUtils::Logger qw(mllogerr);



my $cfg_dir = "./locker";

#sub dispSymbols {
#    my($hashRef) = shift;
#    my(%symbols);
#    my(@symbols);
#
#    %symbols = %{$hashRef};
#    @symbols = sort(keys(%symbols));
#
#    foreach (@symbols) {
#        printf("%-10.10s| %s\n", $_, $symbols{$_});
#    }
#}

#dispSymbols(\%MLUtils::);
#
#exit;


my $server = IO::Socket::INET->new(
    Listen => 5,
    LocalAddr => 'localhost',
    LocalPort => 5050,
    Proto     => 'tcp',
    Listen => 5,
    Reuse => 1,
) or die "Can't create server socket: $!";

while (my $client = $server->accept) {
    my $pid = fork();
    
    if ($pid < 0) {
        die "Fails to fork:$!";
    }
    elsif ($pid > 0) {
        close $client;
    }
    else {
        close $server;
        close(STDOUT);
        close(STDERR); 
        
        while (my $str = <$client>) {
            if ($str =~ /quit/i) {
                close $client;
                last;
            }
            chomp $str;

            if ( open(CMD, "$str |") ) {
                while (<CMD>) {
                    print $client $_;
                }
                #$| = 1;
                print $client "The end.\n";
                close CMD;
            }
            else {
                print $client "$!, please check your CMD <$str>\n";
                print $client "The end.\n";
            }
        }
    }
}

exit 0;

#chomp(my $file_name = <$client>);
#chomp(my $checksum = <$client>);
#open FILE, ">$file_name" or die "Can't open: $!";
#while (<$client>) {
#    if ($_ =~ /reach to end!/) {
#        last;
#    }
#    print FILE $_;
#}
#close FILE;
#
#my $md5 = Digest::MD5->new;
#open(FILE, "$file_name") or die "Error: Could not open file for MD5 checksum, please refer to the usage...";
#binmode(FILE);
#my $md5sum = $md5->addfile(*FILE)->hexdigest; 
#close FILE;
#
#if ($checksum eq $md5sum) {
#    print $client "ok";
#}
#$server->close();